/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package xq.gwt.mvc.controller;


import xq.gwt.mvc.model.CommandModel;
import xq.gwt.mvc.model.PropertyChangedEvent;
import xq.gwt.mvc.model.PropertyChangedListener;
import xq.gwt.mvc.view.CommandView;
import xq.gwt.mvc.view.ViewChangedListener;

/**
 *
 * @author admin
 */
public class CommandController implements ViewChangedListener, PropertyChangedListener{
    private CommandView view;
    private CommandModel commandModel;

    public CommandController(CommandView view){
        this.view = view;
        this.view.addViewChangedListener(this);
    }

    public void setCommandModel(CommandModel commandModel){
        if(this.commandModel != null){
            this.commandModel.isEnabled().removePropertyChangedListener(this);
        }
        this.commandModel = commandModel;
        view.setCaption(this.commandModel.getCaption());
        view.setEnabled(this.commandModel.isEnabled().getValue());
        this.commandModel.isEnabled().addPropertyChangedListener(this);

    }

    private void executeCommand(){
		if(commandModel == null)
            return;
        if(!commandModel.isEnabled().getValue())
            return;
        try {
            view.executeStarted();
			commandModel.execute();

            if(commandModel.getFeedback() != null)
                view.showFeedback(commandModel.getFeedback());
		} catch (Exception ex) {
			view.reportException(ex);
		}
        finally{
            view.excuteFinished();
        }
    }

    public void viewChanged() {
        executeCommand();
    }

    public void propertyChanged(PropertyChangedEvent event) {
        if(event.getSource() == commandModel.isEnabled()){
			view.setEnabled(commandModel.isEnabled().getValue());
		}
    }
}
